package com.urea.system.config;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * @Author: liuzd
 * @Date: 2023/7/30 16:00
 * @Description:
 */
@Configuration
@Slf4j
public class MqttProviderCallBack implements MqttCallback {

    @Value("${spring.mqtt.client.providerid}")
    private String clientId;

    /**
     * 与服务器断开连接的回调
     * @author liuzd
     * @param throwable
     * @return void
     * @date 2023/7/30 16:19
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info( "provider与服务器断开连接,异常信息:{}",throwable.getCause().getMessage());
                log.info("################异常原因:{}##########################", JSONObject.from(throwable).toJSONString());
//        throwable.printStackTrace();
    }

    /**
     * 消息到达的回调
     * @author liuzd
     * @param s
     * @param mqttMessage
     * @return void
     * @date 2023/7/30 16:19
     */
    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
    }

    /**
     * 消息发布成功的回调
     * @author liuzd
     * @param iMqttDeliveryToken
     * @return void
     * @date 2023/7/30 16:20
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//        IMqttAsyncClient client = iMqttDeliveryToken.getClient();
        // todo 是否可在这更新日志
        try {
            if (Objects.nonNull(iMqttDeliveryToken.getMessage())){
                log.info("#########消息成功:{}########",JSONObject.from(iMqttDeliveryToken.getMessage()).toJSONString());
            }else{
                log.info("##########消息发送成功##########");
            }
//            log.info(new String(iMqttDeliveryToken.getMessage().getPayload()) + "发布消息成功！");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}